package xyz.bali16.module.chat.controller;


import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.gitee.starblues.bootstrap.annotation.AutowiredType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import xyz.bali16.application.core.model.Result;
import xyz.bali16.application.core.utils.AuthUtils;
import xyz.bali16.application.entity.User;
import xyz.bali16.application.service.UserService;
import xyz.bali16.module.chat.entity.ChatGroup;
import xyz.bali16.module.chat.entity.ChatGroupUser;
import xyz.bali16.module.chat.entity.ChatUserGroupMessage;
import xyz.bali16.module.chat.model.GroupMessageVO;
import xyz.bali16.module.chat.service.ChatGroupService;
import xyz.bali16.module.chat.service.ChatGroupUserService;
import xyz.bali16.module.chat.service.ChatUserGroupMessageService;
import xyz.bali16.module.chat.websocket.ImConfigConst;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/imChatUserGroupMessage")
public class ChatUserGroupMessageController {

    @Autowired
    private ChatUserGroupMessageService chatUserGroupMessageService;

    @Autowired
    private ChatGroupUserService chatGroupUserService;

    @Autowired
    private ChatGroupService chatGroupService;

    @Autowired
    @AutowiredType(AutowiredType.Type.PLUGIN_MAIN)
    private UserService userService;

    /**
     * 获取群消息（只获取前四十条）
     */
    @GetMapping("/listGroupMessage")
    //@PreAuthorize("@auth.permission('plugin:chat:group:query')")
    public Result<Page> listGroupMessage(@RequestParam(value = "current", defaultValue = "1") Long current,
                                         @RequestParam(value = "size", defaultValue = "40") Long size,
                                         @RequestParam(value = "groupId") Integer groupId) {
        Page<ChatUserGroupMessage> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);


        String username = AuthUtils.getCurrentUsername();
        User user = userService.getByUsername(username);
        String userId = user.getUserId();

        ChatGroup chatGroup = chatGroupService.getById(groupId);
        if (chatGroup == null) {
            return Result.failure("群组不存在！");
        }

        if (chatGroup.getGroupType().intValue() == ImConfigConst.GROUP_COMMON) {
            LambdaQueryChainWrapper<ChatGroupUser> groupLambdaQuery = chatGroupUserService.lambdaQuery();
            groupLambdaQuery.eq(ChatGroupUser::getGroupId, groupId);
            groupLambdaQuery.eq(ChatGroupUser::getUserId, userId);
            groupLambdaQuery.in(ChatGroupUser::getStatus, ImConfigConst.GROUP_USER_STATUS_PASS, ImConfigConst.GROUP_USER_STATUS_SILENCE);
            Integer count = groupLambdaQuery.count();
            if (count < 1) {
                return Result.failure("未加群！");
            }
        }

        LambdaQueryChainWrapper<ChatUserGroupMessage> lambdaQuery = chatUserGroupMessageService.lambdaQuery();
        lambdaQuery.eq(ChatUserGroupMessage::getGroupId, groupId);
        lambdaQuery.orderByDesc(ChatUserGroupMessage::getGmtCreated);
        Page<ChatUserGroupMessage> result = lambdaQuery.page(page);
        List<ChatUserGroupMessage> records = result.getRecords();
        Collections.reverse(records);
        if (CollectionUtils.isEmpty(records)) {
            return Result.success(result);
        } else {
            List<GroupMessageVO> collect = records.stream().map(message -> {
                GroupMessageVO groupMessageVO = new GroupMessageVO();
                groupMessageVO.setContent(message.getContent());
                groupMessageVO.setFromId(message.getFromId());
                groupMessageVO.setToId(message.getToId());
                groupMessageVO.setId(message.getId());
                groupMessageVO.setGroupId(message.getGroupId());
                groupMessageVO.setGmtCreated(message.getGmtCreated());
                String messageUserId = message.getFromId();
                User user = commonQuery.getUser(messageUserId);

                if (user != null) {
                    groupMessageVO.setUsername(user.getUsername());
                    groupMessageVO.setAvatar(user.getAvatar());
                }
                return groupMessageVO;
            }).collect(Collectors.toList());
            Page<GroupMessageVO> resultVO = new Page<>();
            resultVO.setRecords(collect);
            resultVO.setTotal(result.getTotal());
            resultVO.setCurrent(result.getCurrent());
            resultVO.setSize(result.getSize());
            return Result.success(resultVO);
        }
    }
}

